package com.haoshui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.haoshui.constants.SystemConstants;
import com.haoshui.domain.entity.LoginUser;
import com.haoshui.domain.entity.User;
import com.haoshui.mapper.MenuMapper;
import com.haoshui.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service("UserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     *根据用户名查询user信息
     * @param
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, s);
        User user = userMapper.selectOne(queryWrapper);

        //如果用户是空， 抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }


        //判断用户是不是后台用户
        if(user.getType().equals(SystemConstants.IS_ADMIN)){
            List<String> perms = menuMapper.selectPermsByUerId(user.getId());
            return new LoginUser(user, perms);
        }

        return new LoginUser(user, null);
    }
}
